# 自定义用户认证的后端：实现多账号登录
from django.contrib.auth.backends import ModelBackend
from django.conf import settings
import re
from itsdangerous import BadData, TimedJSONWebSignatureSerializer as Serializer

from users.models import User
from celery_tasks.sms import constants


def check_verify_email_token(token):
    """反序列化token, 验证并激活邮箱"""
    serializer = Serializer(settings.SECRET_KEY, expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    try:
        data = serializer.loads(token)
    except BadData:
        return None
    else:
        # 无异常执行此处
        user_id = data.get('user_id')
        email = data.get('email')
        try:
            user = User.objects.get(id=user_id, email=email)
        except User.DonseNotExist:
            return None
        else:
            return user


def generate_verify_email_url(user):
    """
    生成邮箱激活验证链接
    :param user: 当前登录用户
    :return: verify_url
    """
    serializer = Serializer(settings.SECRET_KEY, expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    data = {'user_id': user.id, 'email': user.email}
    token = serializer.dumps(data).decode()
    verify_url = settings.EMAIL_VERIFY_URL + '?token=' + token
    return verify_url


def get_user_by_account(account):
    """
    通过账号获取用户
    :param account: 用户名或手机号
    :return:
    """
    try:
        if re.match(r'^1[3-9]\d{9}$', account):
            # 匹配成功为 username == 手机号
            user = User.objects.get(mobile=account)
        else:
            # username == 用户名
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileBackend(ModelBackend):
    """自定义用户认证后端"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        重写用户认证方法
        :param username: 用户名或手机号
        :param password: 明文密码
        :param kwargs:   额外参数
        :return:  user
        """
        # 检验username是用户名还是手机号
        user = get_user_by_account(username)

        # 可以查询到用户，需要检验密码是否正确
        if user and user.check_password(password):
            return user
        else:
            return None
